<template>
  <div class="mergs-handover-over-container">
    <!-- 交接班选择时间 -->
    <el-card class="box-card" shadow="never">
      <el-form :inline="true" label-position="right"  label-width="90px" :model="orderOptions" size="small" ref='time' class="time-form">
        <el-form-item label="接班时间：">
          <el-date-picker v-model="changeoverTime" type="datetime" align="right" value-format="yyyy-MM-dd HH:mm:ss" placeholder="接班时间" :disabled="!overDisabled" :clearable="false" :picker-options="pickerOptions"></el-date-picker>
        </el-form-item>
        <el-form-item label="交班时间：" style="margin-left: 40px">
          <el-date-picker v-model="shiftTime" type="datetime" align="right" value-format="yyyy-MM-dd HH:mm:ss"  placeholder="交班时间" :picker-options="pickerOptions" :clearable="false"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="selectHandover" style="margin-left: 40px">查询</el-button>
          <el-button @click="confirmShiftTime" class="btn-pri-type" type="primary" style="margin-left: 20px">确认交班</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 交接班本班次汇总数据 -->
    <div class="sum-title">
      <div class="sum-color"></div>
      <div class="sum-text">本班次流水汇总</div>
    </div>
    <div class="box-card-title">
      <div class="title-bottom">本班次时间：{{changeoverTime}}  ~   {{shiftTime}}</div>
    </div>
     <!--存在pos展示内容-->
    <handoverPosTab v-if="showPos" :czbGasDutyRecord="czbGasDutyRecord" :appCzbGasDuty="appCzbGasDuty" :posCzbGasDuty="posCzbGasDuty" :isShowSum="isShowSum" :isShowReal="isShowReal"></handoverPosTab>
    <!--不存在pos兼容老的展示内容-->
    <div class="box-card-content" v-if="!showPos">
      <div class="sumAll">
        <div class="box-card-item">
          <div class="title">收款汇总</div>
          <div v-for="(item,key) in sum" :key="key" class="card-item-text">
            <div v-if="!item.showI">{{item.title}}：{{item.value}}{{item.unit}}</div>
            <el-popover
              v-else
              popper-class="mergs-handover-sum-pop"
              placement="top"
              trigger="hover">
              <div class="pop-container">
                <div class="pop-des"  v-for="(i, k) in item.showI" :key="k">{{i.title}}：{{i.value}}{{i.unit}}</div>
              </div>
              <div class="mergs-handover-pop-title" slot="reference">{{item.title + '（i）'}}：{{item.value}}{{item.unit}}</div>
            </el-popover>
          </div>
        </div>
      </div>
      <div class="sumAll">
        <div class="box-card-item">
          <div class="title">退款汇总</div>
          <div v-for="(item,key) in refund" :key="key" class="card-item-text">
            {{item.title}}：{{item.value}}{{item.unit}}
          </div>
        </div>
      </div>
      <div class="sumAll" v-if="isShowSum">
        <div class="box-card-item">
          <div class="title">结算汇总</div>
          <div v-for="(item,key) in settle" :key="key" class="card-item-text">
              <div v-if="!item.showI">{{item.title}}：{{item.value}}{{item.unit}}</div>
            <el-popover
              popper-class="mergs-handover-set-pop"
              placement="top"
              v-else
              trigger="hover">
              <div class="pop-container">
                <div class="pop-des" v-for="(i, k) in item.showI" :key="k">{{i.title}}：{{i.value}}{{i.unit}}</div>
              </div>
              <div class="mergs-handover-pop-title" slot="reference">{{item.title + '（i）'}}：{{item.value}}{{item.unit}}</div>
            </el-popover>
          </div>
        </div>
      </div>
    </div>
    <!-- 油号交易汇总表格 -->
    <div class="gunNum-wrapper">
      <div class="gunNum-title">
        <div class="title-color"></div>
        <div class="title-text">油号交易汇总</div>
      </div>
      <el-table v-loading="isLoading" size="small" :data="oilNumSummary"  highlight-current-row border  style="width: 100%">
        <template v-if="!showPos">
          <el-table-column v-for="(item, index) in column1" :key="index" :prop="item.dataIndex"  :label="item.title" :align="item.align"></el-table-column>
        </template>
        <template v-else>
          <el-table-column v-for="(item, index) in column1" :key="index" :prop="item.dataIndex"  :label="item.title" :align="item.align">
            <template slot-scope="scope">
              <div v-if="item.dataIndex === 'oilNum'">{{scope.row.oilNum}}</div>
              <!--加油金额部分-->
              <div v-if="item.dataIndex === 'amount'">
                <div class="amount_merge">汇总：{{scope.row.amount || 0}}</div>
                <div class="amount_merge">团油收单：{{scope.row.appDutyGunNumSum.amount || 0}}</div>
                <div>POS收单：{{scope.row.posDutyGunNumSum.amount || 0}}</div>
              </div>
              <!--升数部分-->
              <div v-if="item.dataIndex === 'litre'">
                <div class="amount_merge">汇总：{{scope.row.litre || 0}}</div>
                <div class="amount_merge">团油收单：{{scope.row.appDutyGunNumSum.litre || 0}}</div>
                <div>POS收单：{{scope.row.posDutyGunNumSum.litre || 0}}</div>
              </div>
              <!--订单部分-->
              <div v-if="item.dataIndex === 'count'">
                <div class="amount_merge">汇总：{{scope.row.count || 0}}</div>
                <div class="amount_merge">团油收单：{{scope.row.appDutyGunNumSum.count || 0}}</div>
                <div>POS收单：{{scope.row.posDutyGunNumSum.count || 0}}</div>
              </div>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </div>
    <!-- 枪号交易汇总表格 -->
    <div class="gunNum-wrapper">
      <div class="gunNum-title">
        <div class="title-color"></div>
        <div class="title-text">枪号交易汇总</div>
      </div>
      <el-table v-loading="isLoading" size="small" :data="gunNumSummary"  highlight-current-row border  style="width: 100%">
        <template v-if="!showPos">
          <el-table-column v-for="(item, index) in column2" :key="index" :prop="item.dataIndex"  :label="item.title" :align="item.align"></el-table-column>
        </template>
        <template v-else>
          <el-table-column v-for="(item, index) in column2" :key="index" :prop="item.dataIndex"  :label="item.title" :align="item.align">
            <template slot-scope="scope">
              <div v-if="item.dataIndex === 'gunNo'">{{scope.row.gunNo}}</div>
              <div v-if="item.dataIndex === 'oilNum'">{{scope.row.oilNum}}</div>
              <!--加油金额部分-->
              <div v-if="item.dataIndex === 'amount'">
                <div class="amount_merge">汇总：{{scope.row.amount || 0}}</div>
                <div class="amount_merge">团油收单：{{scope.row.appDutyGunNumSum.amount || 0}}</div>
                <div>POS收单：{{scope.row.posDutyGunNumSum.amount || 0}}</div>
              </div>
              <!--升数部分-->
              <div v-if="item.dataIndex === 'litre'">
                <div class="amount_merge">汇总：{{scope.row.litre || 0}}</div>
                <div class="amount_merge">团油收单：{{scope.row.appDutyGunNumSum.litre || 0}}</div>
                <div>POS收单：{{scope.row.posDutyGunNumSum.litre || 0}}</div>
              </div>
              <!--订单部分-->
              <div v-if="item.dataIndex === 'count'">
                <div class="amount_merge">汇总：{{scope.row.count || 0}}</div>
                <div class="amount_merge">团油收单：{{scope.row.appDutyGunNumSum.count || 0}}</div>
                <div>POS收单：{{scope.row.posDutyGunNumSum.count || 0}}</div>
              </div>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </div>
    <!-- 确认交接班弹窗 -->
    <el-dialog center :visible.sync="isShowDialog">
      <div slot="title">确认交班</div>
      <div style="text-align: center">
        <div style="margin-bottom: 20px">接班时间：{{changeoverTime}}</div>
        <div style="margin-bottom: 20px">交班时间：{{shiftTime}}</div>
        <div>请您再次核对交接班时间，确认现在就要进行交班么？</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" class="btn-pri-type" :loading="handoverLoading"  @click="closeDailog(1)">确 定</el-button>
        <el-button @click="closeDailog(0)">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
import handoverPosTab from './components/handoverPosTab'
import { getChangeoverTime, takeHandover, confirmHandover, getCurrentTime } from '@/api/handover'
import mixin from './mixins'
import _ from 'lodash'

const column1 = [
  { title: '油号', dataIndex: 'oilNum', align: 'center' },
  { title: '加油金额', dataIndex: 'amount', align: 'center' },
  { title: '升数（升）', dataIndex: 'litre', align: 'center' },
  { title: '订单数', dataIndex: 'count', align: 'center' }
]
const column2 = [
  { title: '油枪号', dataIndex: 'gunNo', align: 'center' },
  { title: '油号', dataIndex: 'oilNum', align: 'center' },
  { title: '加油金额（元）', dataIndex: 'amount', align: 'center' },
  { title: '升数（升）', dataIndex: 'litre', align: 'center' },
  { title: '订单数', dataIndex: 'count', align: 'center' }
]
export default {
  // name: 'handover',
  mixins: [mixin],
  components: {
    handoverPosTab
  },
  data () {
    const _this = this
    return {
      showPos: false,
      handoverLoading: false,
      isShowSum: false, // 是否展示汇总
      isActiveType: 1, // 全部汇总-1 团油收单汇总-2 POS收单汇总-5
      cardList: [
        { name: '全部汇总', activeType: 1, interestCode: 'all' },
        { name: '团油收单汇总', activeType: 2, interestCode: 'tuan' },
        { name: 'POS收单汇总', activeType: 3, interestCode: 'pos' }
      ],
      column1,
      column2,
      isLoading: false,
      id: '', // 主键id
      isShowDialog: false,
      orderOptions: {},
      changeoverTime: '', // 接班时间通过接口获取 不能修改 
      shiftTime: '', // 交班时间
      gasDuty: {}, // 本次交易汇总
      czbGasDutyRecord: {}, // 汇总信息tab展示
      appCzbGasDuty: {}, // 团油收单汇总tab展示
      posCzbGasDuty: {}, // pos收单汇总tab展示
      oilNumSummary: [], // 油号交易列表
      gunNumSummary: [], // 枪号交易列表
      serialNo: '',
      overDisabled: true, // 接班时间是否可选
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > moment(_this.rangeTime.maxEndTime).valueOf() || time.getTime() < moment(_this.rangeTime.minStartTime).valueOf()
        }
      },
      rangeTime: {}
    }
  },
  mounted () {
    this.getChangeoverTime()
  },
  methods: {
    setNumber (sum, all) { // 将返回的总数据设置到每一项中
      Object.keys(sum).forEach(key => {
        sum[key].value = all[key]
        if (sum[key].showI) {
          Object.keys(sum[key].showI).forEach(item => {
            sum[key].showI[item].value = all[item]
          })
        }
      })
    },
    // 判断时间是否合适
    async judTime () {
      const { changeoverTime, shiftTime } = this
      let changeoverTime1 = moment(changeoverTime).valueOf() || ''
      let shiftTime1 = moment(shiftTime).valueOf() || ''

      if (shiftTime1 < changeoverTime1) {
        this.$message.error('交班时间需要大于或等于接班时间')
        return false
      }

      const { code, result } = await getCurrentTime()
      if (code !== 200) {
        this.$message.error('无法获取服务器时间')
        return
      }

      if (shiftTime1 > result.timeStamp) {
        this.$message.error('交班时间必须小于或等于系统当前时间')
        return false
      }
      return true
    },
    selectHandover: _.throttle( async function () { // 确认交班时间并查询交班信息
      if(!await this.judTime()) return
      this.takeHandover()
    }, 1000),
    // 确认交接班
    async confirmHandover () {
      this.handoverLoading = true
      this.isLoading = true
      const { changeoverTime, shiftTime } = this
      let params = { dutyStartTime: changeoverTime, dutyEndTime: shiftTime }
      try {
        const { code } = await confirmHandover(params)
        if (code !== 200) return
        this.$message.success('交班成功')
        this.isShowDialog = false
        this.$router.push({ name: 'handoverRecord' })
      } catch (error) {
        console.log(error.message)
      } finally {
        this.handoverLoading = false
        this.isLoading = false
      }
    },
    // 交接班操作(获取交接班信息)
    async takeHandover () {
      this.isLoading = true
      let { changeoverTime, shiftTime } = this
      try {
        const { code, result } = await takeHandover({
          dutyStartTime: changeoverTime,
          dutyEndTime: shiftTime
        })
        if (code !== 200) return
        const { czbGasDutyRecord = {}, appCzbGasDuty = {}, posCzbGasDuty = {},oilNumSumList, gunNumSumList, serialNo, isShowSum, showPos } = result
        let arr = ['sum','refund','settle']
        for (let i = 0; i < arr.length; i++) {
          this.setNumber(this[arr[i]], czbGasDutyRecord) 
        }
        this.showPos = showPos // 是否有pos收单，展示两套样式
        this.isShowSum = isShowSum
        this.czbGasDutyRecord = czbGasDutyRecord // 汇总信息tab展示
        this.appCzbGasDuty = appCzbGasDuty // 团油收单汇总tab展示
        this.posCzbGasDuty = posCzbGasDuty // pos收单汇总tab展示
        this.oilNumSummary = oilNumSumList || []
        this.gunNumSummary = gunNumSumList || []
        this.serialNo = serialNo
      } catch (error) {
        console.log(error.message)
      } finally {
        this.isLoading = false
      }
    },
    // 获取接班时间
    async getChangeoverTime () {
      this.isLoading = true
      try {
        const { code, result } = await getChangeoverTime()
        if (code !== 200) return
        this.overDisabled = result.canSelectStartTime
        this.changeoverTime = result.minStartTime
        this.shiftTime = result.maxEndTime
        this.rangeTime = result
        this.takeHandover()
      } catch (error) {
        console.log(error.message)
      } finally {
        this.isLoading = false
      }
    },
    async confirmShiftTime () { // 确认交班
      if(!await this.judTime()) return
      this.isShowDialog = true
    },
    closeDailog (type) {
      if (type) {
        this.confirmHandover()
      } else {
        this.isShowDialog = false
      }
    }
  }
}
</script>

<style lang="less">
  .mergs-handover-over-container{
    min-width: 80%;
    min-height: 850px;
    padding: 40px 10px;
    box-sizing: border-box;
    background-color: #F8F9FD;
    .time-form{
      margin-top: 20px;
      width: 100%;
      box-sizing: border-box;
    }
    .true-btn{
      transform: translateX(-50%);
    }
    .box-card-title{
      background: #fff;
      width: 100%;
      padding: 11px 0 11px 30px;
      border-radius: 1px;
      box-sizing: border-box;
      margin-bottom: 10px;
    .title-bottom{
      color: #222222;
      font-size: 14px;
    }
  }
  // 兼容以前的老样式
  .box-card-content{
    display: flex;
    .sumAll{
      flex: 1;
      height: 179px;
      padding: 22px 0 0 30px;
      box-sizing: border-box;
      margin-right: 10px;
      border-radius: 1px;
      background: #fff;
      &:last-child{
        margin-right: 0;
        border-right: none;
      }
      .box-card-item{
        width: 100%;
        height: 100%;
        .title{
          font-size:13px;
          font-family:PingFangSC-Bold,PingFang SC;
          font-weight:bold;
          color:rgba(34,34,34,1);
          margin-bottom: 7px;
        }
        .card-item-text{
          font-size:13px;
          font-family:PingFangSC-Regular,PingFang SC;
          font-weight:400;
          color:rgba(122,122,122,1);
          line-height:24px;
        }
      }
    }
  }


  // 卡片切换样式
  .box-tab-content{
    position: relative;
    overflow: hidden;
    .active{
      position: absolute;
      top: 1px;
      z-index: 10;
      >span{
        display: inline-block;
        width: 130px;
        height: 40px;
        font-size:16px;
        font-family: PingFangSC-Bold, PingFang SC;
        margin-right: 5px;
        border:1px solid #DCDFE6;
        border-radius: 15px 15px 0 0;
        text-align: center;
        line-height: 40px;
        cursor: pointer;
      }
      .selected{
        background: #fff;
        color: #000;
        border-bottom: none;
      }
    }
  }
  // 油号交易汇总
  .gunNum-wrapper {
    .gunNum-title{
      width: 100%;
      height: 62px;
      display: flex;
      align-items: center;
      box-sizing: border-box;
      .title-color{
        width: 4px;
        height: 14px;
        background-color: #4B7EFE;
        margin-right: 6px;
      }
      .title-text{
        font-size:16px;
        font-family:PingFangSC-Bold,PingFang SC;
        font-weight:bold;
        color:rgba(34,34,34,1);
      }
    }
    .amount_merge{
      border-bottom: 1px solid #EAEEF4;
    }
  }
  .sum-title{
    width: 100%;
    height: 62px;
    display: flex;
    align-items: center;
    box-sizing: border-box;
    .sum-color{
      width: 4px;
      height: 14px;
      background-color: #4B7EFE;
      margin-right: 6px;
    }
    .sum-text{
      font-size:16px;
      font-family:PingFangSC-Bold,PingFang SC;
      font-weight:bold;
      color:rgba(34,34,34,1);
    }
  }
  .btn-pri-type{
    background: #4B7EFE; 
    border: none;
  }
  .pop-container{
    .pop-des{
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #383838;
      line-height: 25px;
    }
  }
}
.mergs-handover-set-pop{
  padding: 14px!important;
  left: 1078px!important;
}
.mergs-handover-sum-pop{
  padding: 14px!important;
  left: 310px!important;
}
.mergs-handover-pop-title{
  cursor: pointer;
  color: #4B7EFE;
}


</style>
